package com.eunion.web.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eunion.core.LogUtil;

/**
 * 请求的时间的.
 * 
 * 
 * @version 2015-9-11
 */
public class ExecuteTimeInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteTimeInterceptor.class);

    /**
     * before the actual handler will be executed.
     * 
     * @param request
     *            http request
     * @param response
     *            http response
     * @param handler
     *            handler
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        request.setAttribute(LogUtil.START, System.currentTimeMillis());
        return true;
    }

    /**
     * after the handler is executed.
     * 
     * @param request
     *            http request
     * @param response
     *            http response
     * @param handler
     *            handler
     * @param modelAndView
     *            modelAndView
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {
        long executeTime = System.currentTimeMillis() - (Long) request.getAttribute(LogUtil.START);
        // modified the exisitng modelAndView
        // modelAndView.addObject("executeTime", executeTime);
        LOGGER.debug("[{}] executeTime : {}.{} s", handler, executeTime / 1000, executeTime % 1000);
    }
}
